package com.luo.d3s.ext.event.jdbc.convertor;

import com.luo.d3s.core.domain.event.DomainEvent;
import com.luo.d3s.core.domain.event.DomainEventStatus;
import com.luo.d3s.core.util.JsonUtils;
import com.luo.d3s.ext.event.jdbc.dataobject.DomainEventDo;


/**
 * 领域事件转换器
 *
 * @author luohq
 * @date 2022-12-21 10:30
 */
public class DomainEventConvertor {


    public static DomainEventDo toEventDo(DomainEvent domainEvent) {
        DomainEventDo domainEventDo = new DomainEventDo();
        domainEventDo.setId(String.valueOf(domainEvent.getEventId()));
        domainEventDo.setCreateTime(domainEvent.getCreateTime());
        domainEventDo.setStatus(DomainEventStatus.CREATED.getStatus());
        domainEventDo.setAggregateId(String.valueOf(domainEvent.getAggregateRootId()));
        domainEventDo.setJsonType(domainEvent.getClass().getName());
        domainEventDo.setJsonContent(JsonUtils.toJson(domainEvent));
        return domainEventDo;
    }

    public static <T extends DomainEvent> T toEvent(DomainEventDo domainEventDo) {
        try {
            Class<T> jsonTypeClass = (Class<T>) Class.forName(domainEventDo.getJsonType());
            return JsonUtils.fromJson(domainEventDo.getJsonContent(), jsonTypeClass);
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        }
    }
}
